package com.tricky.tron.trc20.service;

import com.tricky.tron.trc20.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountService {
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 根据账户名查找
     * @param coinUnit
     * @param username
     * @return
     */
    public Account findByName(String coinUnit, String username){
        Query query = new Query();
        Criteria criteria = Criteria.where("account").is(username);
        query.addCriteria(criteria);
        return mongoTemplate.findOne(query,Account.class,getCollectionName(coinUnit));
    }



    public String getCollectionName(String coinUnit){
        return coinUnit + "_address_book";
    }

    public void removeByName(String name){
        Query query = new Query();
        Criteria criteria = Criteria.where("account").is(name);
        query.addCriteria(criteria);
        mongoTemplate.remove(query,getCollectionName("TRX"));
    }

    /**
     * 获取所有账户
     * @return
     */
    public List<Account> findAll() {
        return mongoTemplate.findAll(Account.class,getCollectionName("TRX"));
    }


    public void save(Account account,String coinUnit){
        mongoTemplate.insert(account,getCollectionName(coinUnit));
    }

    public void saveOne(String username, String privateKey, String address) {
        removeByName(username);
        Account account = new Account();
        account.setAccount(username);
        account.setAddress(address.toLowerCase());
        account.setPrivateKey(privateKey);
        save(account,"TRX");
    }
}
